<template>
  <el-dialog
    v-dialogDrag
    :visible.sync="dialogVisible"
    :title="title"
    width="1100px"
    @close="resetForm('ruleForm')"
  >
    <button-group
      ref="buttonGroup"
      @submitForm="submitForm('ruleForm')"
      @cancel="dialogVisible = false"
    />
    <div class="formTopFont">销售出库单</div>
    <el-row>
      <el-form
        ref="ruleForm"
        :model="ruleForm"
        :rules="rules"
        label-width="auto"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item label="销售单号" prop="saleOrderId">
              <el-select
                v-model="ruleForm.saleOrderId"
                v-if="title === '新增'"
                style="width: 100%"
                @change="getNoList"
              >
                <el-option
                  v-for="item in outlssueNoList"
                  :key="item.id"
                  :label="`${item.saleNo}`"
                  :value="item.id"
                >
                  <span style="float: left">{{ item.saleNo }}</span>
                </el-option>
              </el-select>
              <el-input v-else v-model="ruleForm.saleNo" disabled />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="出库单号" prop="outNo">
              <el-input
                v-model="ruleForm.outNo"
                maxlength="20"
                show-word-limit
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="出库日期" prop="outDate">
              <el-date-picker
                v-model="ruleForm.outDate"
                type="date"
                placeholder="选择日期时间"
                style="width: 100%"
                format="yyyy-MM-dd"
                value-format="yyyy-MM-dd"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="出库人" prop="userId">
              <el-select v-model="ruleForm.userId" style="width: 100%">
                <el-option
                  v-for="item in userAllList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="客户名称" prop="customerName">
              <el-input v-model="ruleForm.customerName" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否完成" prop="isFinish">
              <el-checkbox
                v-model="ruleForm.isFinish"
                :true-label="1"
                :false-label="0"
              ></el-checkbox>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input
                v-model="ruleForm.remark"
                maxlength="200"
                type="textarea"
                rows="2"
                show-word-limit
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <el-row v-if="ruleForm.saleOrderId">
        <el-col :span="12" style="padding-right: 5px">
          <h1 class="titleH1">订单信息</h1>
          <el-table
            border
            stripe
            height="220px"
            highlight-current-row
            @row-click="handClick"
            :data="materialAll"
          >
            <el-table-column label="物料" width="150px" align="center">
              <template #default="{ row }"
                >{{ row.materialName }}
                {{
                  row.materialCode ? "【" + row.materialCode + "】" : ""
                }}</template
              >
            </el-table-column>
            <el-table-column
              prop="unit"
              label="单位"
              width="80px"
              align="center"
            />
            <el-table-column
              prop="num"
              label="订单数量"
              width="100px"
              align="center"
            />
            <el-table-column
              prop="price"
              label="销售单价"
              width="100px"
              align="center"
            />
            <el-table-column
              prop="residueNum"
              label="未配货数量"
              width="100px"
              align="center"
            />
          </el-table>
        </el-col>
        <el-col :span="12" style="padding-left: 5px">
          <h1 class="titleH1">仓库库存信息</h1>
          <el-table
            border
            class="tabOver"
            stripe
            height="220px"
            :data="rightInfo"
          >
            <el-table-column
              prop="num"
              label="库存数量"
              show-overflow-tooltip
              v-if="title === '新增'"
              min-width="70px"
              align="center"
            />
            <el-table-column
              prop="price"
              label="库存单价"
              show-overflow-tooltip
              v-if="title === '新增'"
              min-width="70px"
              align="center"
            />
            <el-table-column
              prop="wmsName"
              label="库房"
              show-overflow-tooltip
              min-width="100px"
              align="center"
            />
            <el-table-column
              prop="batch"
              label="批次"
              show-overflow-tooltip
              min-width="80px"
              align="center"
            />
            <el-table-column
              prop="outNum"
              align="center"
              show-overflow-tooltip
              min-width="100px"
            >
              <template slot="header">
                <span style="color: #f56c6c">*</span>出库数量
              </template>
              <template #default="{ row }">
                <el-input-number
                  v-if="title === '新增'"
                  v-model="row.outNum"
                  :disabled="title === '编辑'"
                  size="mini"
                  :max="row.num"
                  :controls="false"
                  :min="1"
                  style="width: 100%"
                />
                <span v-else>{{ row.outNum }}</span>
              </template>
            </el-table-column>
            <el-table-column
              prop="outPrice"
              align="center"
              show-overflow-tooltip
              min-width="100px"
            >
              <template slot="header">
                <span style="color: #f56c6c">*</span>出库单价
              </template>
              <template #default="{ row }">
                <el-input-number
                  v-if="title === '新增'"
                  v-model="row.outPrice"
                  :disabled="title === '编辑'"
                  size="mini"
                  :controls="false"
                  :precision="2"
                  :min="1"
                  style="width: 100%"
                />
                <span v-else>{{ row.outPrice }}</span>
              </template>
            </el-table-column>
          </el-table>
        </el-col>
      </el-row>
    </el-row>
    <bottom-font
      v-if="title === '编辑'"
      ref="bottomFont"
      :obj-name="ruleForm.userName"
      :rew-name="ruleForm.reviewer"
      :obj-date="ruleForm.outDate"
    />
  </el-dialog>
</template>
<script>
import { timeFormatToString } from "@/utils/function";
import bottomFont from "@/components/BottomFont";
export default {
  components: { bottomFont },
  props: {
    userAllList: {
      type: Array,
      default: () => {
        return {};
      },
    },
    customerAllList: {
      type: Array,
      default: () => {
        return {};
      },
    },
  },
  data() {
    const checkLssueNo = async (rule, value, callback) => {
      const res = await this.$axios.get(
        `/sale/out/verifyNoUnique?no=${value}&id=${this.ruleForm.outId || ""}`
      );
      if (res?.data.code === 200) {
        return res.data.data
          ? callback()
          : new Error(callback("出库单号重复！"));
      } else {
        return new Error(callback(res.data.msg));
      }
    };
    return {
      title: "",
      ruleForm: {
        customerName: "",
        customerId: "", // 客户名称
        outNo: "", // 出库单号
        userId: "", // 出库人主键
        outDate: timeFormatToString(new Date()).slice(0, 10), // 出库日期
        saleOrderId: "",
        saleNo: "", // 销售单号
        materials: [],
        isFinish: 0,
        remark: "",
      },
      rules: {
        saleOrderId: [
          { required: true, message: "清选择销售单号！", trigger: "change" },
        ],
        outNo: [
          { required: true, message: "出库单号不能为空！", trigger: "blur" },
          { validator: checkLssueNo, trigger: "blur" },
        ],
        outDate: [
          { required: true, message: "清选择出库日期！", trigger: "change" },
        ],
      },
      dialogVisible: false,
      outlssueNoList: [],
      materialAll: [],
      detailInfo: [],
      copyList: [],
      rightInfo: [],
    };
  },
  watch: {},
  mounted() {},
  methods: {
    /**
     * @description: 新增编辑
     * @param {*} row
     * @return {*}
     */
    async showDialog(row) {
      this.getOutlssueNo();
      if (row && row.hasOwnProperty("id")) {
        this.title = "编辑";
        const res = await this.$axios.get(`/sale/out/detail?id=${row.id}`);
        if (res?.data.code === 200) {
          this.ruleForm = Object.assign({}, res.data.data);
          this.ruleForm.saleOrderId = res.data.data.id;
          this.materialAll = res.data.data.materials;
          this.handClick(this.materialAll[0]);
        }
      } else {
        this.title = "新增";
      }
      this.dialogVisible = true;
    },
    /* 获取销售单号 */
    async getOutlssueNo() {
      const res = await this.$axios.get(`/sale/out/search`);
      if (res.data.code === 200) {
        this.outlssueNoList = res.data.data;
      }
    },
    /* 用销售id获取物料 */
    async getNoList($event) {
      const { saleNo, id, customerName, customerId } = this.outlssueNoList.find(
        (item) => item.id === $event
      );
      this.ruleForm.saleNo = saleNo;
      this.ruleForm.customerName = customerName;
      this.ruleForm.customerId = customerId;
      const res = await this.$axios.get(`/sale/out/searchMaterial?id=${id}`);
      if (res?.data.code === 200) {
        res.data.data.forEach((item) => {
          if (item.wmsInfos.length > 0) {
            item.wmsInfos.forEach((itx) => {
              this.copyList.push(itx);
            });
          }
        });
        this.materialAll = res.data.data;
        this.handClick(this.materialAll[0]);
      }
    },
    /* 左侧物料表格行点击事件 */
    handClick(row) {
      if (this.title === "编辑") {
        this.rightInfo = row.outMaterials;
      } else {
        this.rightInfo = row.wmsInfos;
      }
    },
    /**
     * @description: 表单提交
     * @param {*} formName
     * @return {*}
     */
    submitForm(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          if (this.title === "新增") {
            /* 判断库房出库数量必须有一条是填的 */
            let arr = [];
            this.copyList.forEach((item) => {
              if (item.outNum !== undefined) {
                arr.push(item);
              }
            });
            if (arr.length > 0) {
              /* 判断库房出库数量填了那出库单价必须也填 */
              const hasEmptyList = [];
              arr.forEach((item, index) => {
                if (item.outNum !== null && item.outPrice === undefined) {
                  hasEmptyList.push(index + 1);
                }
              });
              if (hasEmptyList.length) {
                this.$alert(
                  `请完善单价，序号：${hasEmptyList
                    .toString()
                    .replace(/,/g, "、")} !`,
                  "提示",
                  {
                    confirmButtonText: "确认",
                    type: "warning",
                  }
                );
              } else {
                const params = {
                  ...this.ruleForm,
                  materials: arr,
                };
                this.saveApi(params);
              }
            } else {
              this.$alert(`请维护一条出库信息!`, "提示", {
                confirmButtonText: "确认",
                type: "warning",
              });
            }
          } else {
            this.saveApi(this.ruleForm);
          }
        }
      });
    },
    async saveApi(params) {
      const res = await this.$axios.post("/sale/out/save", params);
      if (res?.data.code === 200) {
        this.$notify.success("提交成功！");
        this.dialogVisible = false;
        this.$emit("getTableInfo");
      } else {
        this.$notify.error(res.data.msg);
      }
    },
    /**
     * @description: 重置表单
     * @param {*} formName
     * @return {*}
     */
    resetForm(formName) {
      this.$refs[formName].resetFields();
      this.ruleForm = Object.assign({}, this.$options.data.call(this).ruleForm);
      this.materialAll = [];
      this.detailInfo = [];
    },
  },
};
</script>
<style lang="scss" scoped>
.highlight-row {
  background: red;
}
</style>
